package com.android.task6;

import java.util.ArrayList;

import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.content.ContentProviderOperation.Builder;
import android.database.Cursor;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.util.Log;

public class ContactManager {
	
	ContentProvider cp;
	ContentResolver cr;
	ContactSharing activity;
	
	public ContactManager(ContentResolver cr){
		this.cr = cr;
	}

	public void setActivity(ContactSharing activity){
		this.activity = activity;
	}
	
	/**
	 *  Returns a contact with the given display name. Only name, phone numbers
	 *  and email addresses are returned.
	 */
	
	public Contact getContact(String displayName){

		String[] nameParts = displayName.split(" ");
		
		String firstName = nameParts[0];
		String lastName = "";
		for(int i = 1; i < nameParts.length; i++){
			lastName += nameParts[i]+" ";
		}
		lastName = lastName.trim();
		
		boolean found = false;
		Contact contact = null;
		Cursor cursor = this.cr.query(ContactsContract.Contacts.CONTENT_URI, 
				null, null, null, null); 

		while(cursor.moveToNext() && !found){
			String contactId = cursor.getString(cursor.getColumnIndex( 
					ContactsContract.Contacts._ID)); 
			String tmpName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

			if(tmpName.trim().equalsIgnoreCase(displayName.trim())){
				found = true;
				contact = new Contact(firstName,lastName,"","");

				Cursor phones = this.cr.query( 
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
						null, 
						ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, 
						null, null);

				while(phones.moveToNext()){
					String phoneNumber = phones.getString( 
							phones.getColumnIndex( 
									ContactsContract.CommonDataKinds.Phone.NUMBER));
					contact.setPhoneNumber(phoneNumber);

				}
				phones.close();
				Cursor emails = this.cr.query( 
						ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
						null, 
						ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, 
						null, null); 
				
				while (emails.moveToNext()) { 
					// This would allow you get several email addresses 
					String emailAddress = emails.getString( 
							emails.getColumnIndex( 
									ContactsContract.CommonDataKinds.Email.DATA));
					contact.setEmailAddress(emailAddress);
				} 
				emails.close(); 

			}
		}
		return contact;
	}
	
	/**
	 *  Adds a new contact to the contact database.
	 *  first name, last name, phone number and email address are added.
	 */
	public void writeContact(Contact contact){
		Log.i("bt","writes contact");
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		
		String accountType =null;
		String accountName = null;
		
		Builder builder = ContentProviderOperation.newInsert(
				ContactsContract.RawContacts.CONTENT_URI);
		builder.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType);
		builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName);
		
		ContentProviderOperation op = builder.build();

		ops.add(op);
		
		ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
				.withValueBackReference(
						ContactsContract.Data.RAW_CONTACT_ID,
						0)
						.withValue(
								ContactsContract.Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE)
								.
						withValue(
								ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contact.getFullName())
						.build());
		
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.getPhoneNumber())
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
                .build());
        
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Email.DATA, contact.getEmailAddress())
                .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME)
                .build());	
		 
        try {
			this.cr.applyBatch(ContactsContract.AUTHORITY, ops);
			this.activity.showDialog(R.string.new_contact,"New contact: "+contact.getFullName());
		}
		 
		 catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OperationApplicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

